import React from 'react';
import {connect} from 'react-redux'
import config from 'config';
import menuRoute from 'routes/menuRoute'
import {Table, Button, Popover, Modal, Form, Input, Row, Col, Radio, Icon, Upload, message, Select, Switch} from 'antd';
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const Option = Select.Option;
import {LanguageInput} from 'components/index';
import {messages} from "share/common";
import moment from "moment";
import subApplicationService from 'containers/setting/sub-application/sub-application.service'
import configureStore from "stores";
import ResizeTable from "components/resize-table";

class EditSubApplicationRecord extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      appCode: props.appCode,
      appName: props.appName,
      data: [],
      fileList: [],
      page: 0,
      pagination: {
        total: 0,
        showQuickJumper: true,
      },
      visible: false,
      columns: [
        {
          title: messages('setting.key1971')/*版本号*/, dataIndex: 'appLevel', width: "6%", render: (text) => {
            return (
              <Popover content={text}
                       placement={'topLeft'}
                       overlayClassName={'tenant-maintenance-popover'}
                       overlayStyle={{whiteSpace: 'pre-wrap', maxWidth: 350}}>
                <div>{text}</div>
              </Popover>
            )
          }
        },
        {
          title: messages('setting.key2062')/*主版本号*/, dataIndex: 'appMainVersion', width: "8%", render: (text) => {
            return (
              <Popover content={text}
                       placement={'topLeft'}
                       overlayClassName={'tenant-maintenance-popover'}
                       overlayStyle={{whiteSpace: 'pre-wrap', maxWidth: 350}}>
                <div>{text}</div>
              </Popover>
            )
          }
        },
        {
          title: messages('setting.key2077')/*更新人*/, dataIndex: 'userName', width: "10%", render: (text) => {
            return (
              <Popover content={text}
                       placement={'topLeft'}
                       overlayClassName={'tenant-maintenance-popover'}
                       overlayStyle={{whiteSpace: 'pre-wrap', maxWidth: 350}}>
                <div>{text}</div>
              </Popover>
            )
          }
        },
        {
          title: messages('setting.key2078')/*更新时间*/, dataIndex: 'lastUpdatedDate', width: "14%", render: (text) => {
            return (
              <Popover content={moment(text).format("YYYY-MM-DD HH:mm:ss")}
                       placement={'topLeft'}
                       overlayClassName={'tenant-maintenance-popover'}
                       overlayStyle={{whiteSpace: 'pre-wrap', maxWidth: 350}}>
                <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div>
              </Popover>
            )
          }
        },
        {
          title: messages('setting.key1031')/*描述*/, dataIndex: 'releaseNote', render: (text) => {
            return (
              <Popover content={text}
                       placement={'topLeft'}
                       overlayClassName={'tenant-maintenance-popover'}
                       overlayStyle={{whiteSpace: 'pre-wrap', maxWidth: 350}}>
                <div>{text}</div>
              </Popover>
            )
          }
        },
        {
          title: messages('setting.key2063')/*操作系统*/, dataIndex: 'platform', width: "8%", render: (text) => {
            return (
              <Popover content={text}
                       placement={'topLeft'}
                       overlayClassName={'tenant-maintenance-popover'}
                       overlayStyle={{whiteSpace: 'pre-wrap', maxWidth: 350}}>
                <div>{text}</div>
              </Popover>
            )
          }
        },
        {
          title: messages('setting.key2061')/*强制更新*/, dataIndex: 'mandatory', width: "8%", render: (text) => {
            return (text ? messages('setting.key1393')/*是*/ : messages('setting.key1394')/*否*/)
          }
        },
        {
          title: messages('setting.key1147')/*操作*/, dataIndex: 'operation', width: "6%", render: (text, record) => {
            return (
              <a onClick={(e) => {
                this.goToDetail(e, text, record)
              }}>{messages('setting.key202')/*详情*/}</a>
            )
          }
        },
      ],
      subApplicationData: {
        releaseNote: " ",//名称
        i18n: {}//包含名称,描述
      },
      versionOptions: [],
      subAppVersionRecordDetail: menuRoute.getRouteItem('sub-application-version-detail', 'key').url,   //新建子应用的页面项
    }
  }

  componentWillMount() {
    this.getSubApplicationVersionList();
    // this.getVersionOptions ();
  }

  goToDetail = (e, text, record) => {
    const {subAppVersionRecordDetail, appCode, appName} = this.state;
    this.context.router.push({
      pathname: subAppVersionRecordDetail.replace(":code", appCode).replace(":id", record.sourceId),
      state: {
        appCode: record.appCode,
        appLevel: record.appLevel,
        appName: appName,
      }
    })
  };

  //获取系统消息列表
  getSubApplicationVersionList = () => {
    const {page, appCode} = this.state;
    this.setState({
      loading: true,
    });
     subApplicationService.getVersionRecordList(appCode, page).then(res => {
        this.setState({
          data: res.data,
          loading: false,
          pagination: {
            total: Number(res.headers['x-total-count']),
            current: this.state.page + 1,
            onChange: this.onChangePaper,
          }
        })
      }
    ).catch(err => {
      this.setState({
        loading: false,
      });
    })
  };

  //获取最小版本选项
  getVersionOptions = () => {
    const {appCode} = this.state;
     subApplicationService.getVersionOptions(appCode, '').then(res => {
      this.setState({
        versionOptions: res.data,
      })
    }).catch(err => {

    })
  };

  //点击分页
  onChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({
          page: page - 1,
        }, () => {
          this.getSubApplicationVersionList();
        }
      )
    }
  };

  //上传文件时
  handleUploadChange = (file) => {
    if (file.fileList.length) {
      if (!file.fileList[0].name.endsWith('.zip')) {
        message.error(messages('setting.key2079')/*请上传zip文件*/)
      } else {
        this.setState({
          fileList: file.fileList,
        })
      }
    } else {
      this.setState({
        fileList: file.fileList,
      })
    }
  };

  onClickNew = () => {
    this.setState({
      visible: true,
    })
  };

  onModalOk = () => {
    const {fileList, appCode, subApplicationData, source, sectionId} = this.state;
    if (!fileList.length) {
      message.error(messages('setting.key2066')/*请上传代码资源*/)
    } else {
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          this.setState({
            loading: true,
          });
          values.downloadLink = fileList[0].fileUrl || fileList[0].response.fileURL;
          values.appCode = appCode;
          values.source = (sectionId === 2 || sectionId === '2' ? 'VENDOR' : 'WORK');
          values.isPublic = true;
          values.i18n = subApplicationData.i18n;
           subApplicationService.editVersionRecord(values).then(res => {
            subApplicationData.i18n = {};
            this.setState({
              visible: false,
              loading: false,
              fileList: [],
              subApplicationData,
            });
            this.props.form.resetFields();
            this.getSubApplicationVersionList();
          }).catch(err => {
            this.setState({
              loading: false,
            });
          });
        } else {
          this.setState({
            loading: false,
          });
        }
      });
    }
  };

  onModalCancel = () => {
    const {subApplicationData} = this.state;
    this.props.form.resetFields();
    subApplicationData.i18n = {};
    this.setState({
      visible: false,
      fileList: [],
      subApplicationData,
    })
  };

  //子应用名称：多语言
  i18nAppNameChange = (name, i18nName) => {
    const subApplicationData = this.state.subApplicationData;
    subApplicationData.releaseNote = name;
    if (!subApplicationData.i18n) {
      subApplicationData.i18n = {};
    }
    subApplicationData.i18n.releaseNote = i18nName;
  };

  render() {
    const {pagination, data, columns, loading, visible, fileList, appName, subApplicationData} = this.state;
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14},
    };
    const uploadButton = (
      <div>
        <Button>
          <Icon type="upload"/> {messages('setting.key2080')/*上传.zip文件*/}
        </Button>
      </div>
    );
    const upload_headers = {
      // 'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('hly.token')).access_token
      'Authorization': 'Bearer ' + configureStore.store.getState().main.authToken.access_token
  }
    ;
    return (
      <div>
        <Button style={{marginBottom: 20}} type={'primary'} onClick={this.onClickNew}>{messages('setting.key2081')/*新建版本*/}</Button>
        <ResizeTable
          dataSource={data}
          columns={columns}
          size={'middle'}
          loading={loading}
          bordered
          rowKey={'id'}
          pagination={pagination}
        />
        <Modal
          visible={visible}
          title={messages('setting.key2081')/*新建版本*/}
          destroyOnClose={true}
          maskClosable={false}
          onCancel={this.onModalCancel}
          onOk={this.onModalOk}
          confirmLoading={loading}
          okText={messages('setting.key1079')/*保存*/}
        >
          <Form>
            <FormItem {...formItemLayout} label={messages('setting.key1096')/*状态*/}>
              {getFieldDecorator('enabled', {
                initialValue: true,
                valuePropName: "checked",
                rules: [{
                  required: false,
                }]
              })
              (<Switch/>)
              }
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key1026')/*应用名称*/}>
              {getFieldDecorator('name', {
                initialValue: appName,
                rules: [{
                  required: false,
                }]
              })
              (<Input placeholder={messages('common.please.input')/*请输入*/} disabled/>)
              }
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key2062')/*主版本号*/}>
              {getFieldDecorator('appMainVersion', {
                initialValue: '',
                rules: [{
                  required: true,
                  message: messages('setting.key2075')/*主版本号不能为空*/
                }]
              })
              (<Input placeholder={messages('common.please.input')/*请输入*/}/>)
              }
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key2064')/*版本描述*/}>
              {getFieldDecorator('releaseNote', {
                initialValue: '',
                rules: [{
                  required: false
                }]
              })
              (
                <LanguageInput
                  key={1}
                  name={subApplicationData.releaseNote}
                  i18nName={subApplicationData.i18n && subApplicationData.i18n.releaseNote ? subApplicationData.i18n.releaseNote : null}
                  placeholder={messages("setting.key524")/* 请输入，最多20个字符 */}
                  isEdit={subApplicationData.id}
                  nameChange={this.i18nAppNameChange}/>
              )
              }
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key2063')/*操作系统*/}>
              {getFieldDecorator('platform', {
                initialValue: '',
                rules: [{
                  required: true,
                  message: messages('setting.key2075')/*主版本号不能为空*/
                }]
              })
              (<Select placeholder={messages('setting.key1137')/*请选择*/}>
                <Option value={'iOS'}>iOS</Option>
                <Option value={'ANDROID'}>ANDROID</Option>
              </Select>)
              }
            </FormItem>
          </Form>
          <Row style={{marginBottom: 24}}>
            <Col span={6}>
              <span style={{color: 'red', marginLeft: 35}}>*</span>
              <span style={{color: 'black'}}>&nbsp;{messages('setting.key2065')/*代码资源*/}：</span>
            </Col>
            <Col span={16}>
              <Upload action={`${config.baseUrl}/api/upload/static/attachment`}
                      headers={upload_headers}
                      fileList={fileList}
                      accept={'.zip'}
                      data={{attachmentType: 'OTHER'}}
                      onChange={this.handleUploadChange}>
                {fileList.length >= 1 ? null : uploadButton}
              </Upload>
            </Col>
          </Row>
          <Form>
            <FormItem {...formItemLayout} label={messages('setting.key2061')/*强制更新*/}>
              {getFieldDecorator('mandatory', {
                initialValue: false,
                rules: [{
                  required: true,
                  message: messages('setting.key2076')/*强制更新不能为空*/
                }]
              })
              (<RadioGroup>
                <Radio value={true}>{messages('setting.key1393')/*是*/}</Radio>
                <Radio value={false}>{messages('setting.key1394')/*否*/}</Radio>
              </RadioGroup>)
              }
            </FormItem>
            {/*<FormItem {...formItemLayout}*/}
            {/*label={<span><span style={{color: 'red', display: this.props.form.getFieldValue('mandatory') ? 'none' : 'inline'}}>*</span>&nbsp;最小版本</span>}>*/}
            {/*{getFieldDecorator('minUpdateVersion', {*/}
            {/*initialValue: '',*/}
            {/*rules: [*/}
            {/*{*/}
            {/*pattern: /^[0-9]/,*/}
            {/*message: '请输入正整数',*/}
            {/*},*/}
            {/*{*/}
            {/*required: false,*/}
            {/*}*/}
            {/*]*/}
            {/*})*/}
            {/*(*/}
            {/*<Select showSearch={true}*/}
            {/*allowClear={true}*/}
            {/*optionFilterProp="children"*/}
            {/*placeholder={messages('common.please.select')}*/}
            {/*getPopupContainer={triggerNode => triggerNode.parentNode}>*/}
            {/*{this.state.versionOptions.map((item, index) => {*/}
            {/*return <Option key={index} value={item}>{item}</Option>*/}
            {/*})}*/}
            {/*</Select>*/}
            {/*)*/}
            {/*}*/}
            {/*</FormItem>*/}
          </Form>
        </Modal>
      </div>
    )
  }
}

EditSubApplicationRecord.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {}
}

const WrappedSubApplicationVersionRecord = Form.create()(EditSubApplicationRecord);
export default connect(mapStateToProps)(WrappedSubApplicationVersionRecord);
